import NavBar from '@/components/Global/NavBar'
import { Button } from 'antd-mobile'
import { useEffect, useState } from 'react'
import { fetchCourseList } from '../api'
import styles from './index.module.less'
import type { CourseDetail } from '../detail/interface'
import { history } from 'umi'
import { SkeletonParagraphWrap } from '@/components/Common/Skeleton'

type Props = {
    courseId: number
    courseName: string
    imgPath: string
    lessonsTotal: number
}

const CourseItem = (props: Props) => {
    const goLearn = () => {
        history.push({ pathname: '/onlineClass/detail', query: { id: String(props.courseId) } })
    }

    return (
        <div className={styles.courseBox}>
            <div className={styles.detail}>
                <div
                    style={{
                        backgroundImage: `url('${props.imgPath}')`,
                    }}
                    className={styles.detail_cover}
                />
                <div className={styles.detail_info}>
                    <div className={styles.detail_info_name}>{props.courseName || '-'}</div>
                    <div className={styles.detail_info_chapter}>{`视频数：${
                        props.lessonsTotal ?? 0
                    }节`}</div>
                </div>
            </div>
            <div className={styles.splitLine} />
            <div className={styles.operate}>
                <Button className={styles.button} onClick={goLearn}>
                    去学习
                </Button>
            </div>
        </div>
    )
}

export const OnlineClass = () => {
    const [loading, setLoading] = useState<boolean>(false)
    const [courseList, setCourseList] = useState<Record<string, CourseDetail>>({})

    useEffect(() => {
        const initData = async () => {
            try {
                setLoading(true)
                const { data } = await fetchCourseList()
                setCourseList(data)
            } finally {
                setLoading(false)
            }
        }
        initData()
    }, [])

    return (
        <div>
            <NavBar title="在线课堂" />
            <div className={styles.page}>
                <div className={styles.courses}>
                    <SkeletonParagraphWrap animated lineCount={10} loading={loading}>
                        {Object.entries(courseList).map(([k, v]) => {
                            return <CourseItem key={k} {...v} />
                        })}
                    </SkeletonParagraphWrap>
                </div>
            </div>
        </div>
    )
}

export default OnlineClass
